<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传</title>
</head>

<body>
    <input type="file" id="fileUp" accept="image/*">
    <img id="serverImg">
    <script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.16.0/js/md5.min.js"></script>
    <script src="./js/ajax.js"></script>
    <script>
        fileUp.onchange = async function (e) {
            let file = fileUp.files[0];
            let { hash, suffix, filename } = $formatFileName(file.name);
            //切片
            let partList = [], cur = 0, partSize = file.size / 5;
            for (let i = 0; i < 5; i++) {
                let formData = new FormData();
                formData.append('chunk', file.slice(cur, cur + partSize));
                formData.append('filename', `${hash}-${i}.${suffix}`);
                formData.append('dirname', hash);
                partList.push(formData);
                cur += partSize;
            }
            //请求
            partList = partList.map(item => {
                $ajax({
                    url: "http://127.0.0.1:4000/chunk",
                    data: item
                }).then(res => {
                    if (res.code === 0) {
                        return Promise.resolve(res);
                    }
                    return Promise.reject(res);
                })
            })
            //合并切片
            await Promise.all(partList);
            let time = Date.now();
            while (Date.now() - time < 1000);
            let res = await $ajax({
                url: "http://127.0.0.1:4000/merge",
                headers: {
                    'Content-Type': 'application/x-wwww-form-urlencoded'
                },
                data: `filename=${filename}`
            })
            console.log(res)
            serverImg.src = res.imgSrc;
        }
    </script>
</body>

</html>